﻿using Consul;
using Developer.Core.FrameWork.RegisterCenter.Model;
using Developer.Core.FrameWork.RegisterCenter.Options;
using Developer.Core.FrameWork.RegisterCenter.Service;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;

namespace Developer.Core.FrameWork.RegisterCenter.Consul
{
    /// <summary>
    /// Consul服务发现
    /// </summary>
    public class ConsulServiceDiscovery : AbstractServiceDiscovery
    {
        public ConsulServiceDiscovery(IOptions<ServiceDiscoveryOptions> options) : base(options)
        {
        }

        protected override CatalogService[] RemoteDiscovery(string serviceName)
        {
            var consulClient = new ConsulClient(configuration =>
            {
                configuration.Address = new Uri(serviceDiscoveryOptions.DiscoveryAddress);
            });

            var query = consulClient.Catalog.Service(serviceName).Result;

            if (query.StatusCode.Equals(HttpStatusCode.OK))
                throw new ArgumentNullException("consul连接异常");

            return query.Response;
        }
    }
}
